package com.david.reader.utils

import android.os.Environment
import com.david.reader.bean.BookBean

class BookHelper {
    companion object{
        var instance: BookHelper = BookHelper()
    }

    lateinit var bookList:ArrayList<BookBean>

    fun loadList():ArrayList<BookBean>{
        if (isBookListInit()) {
            return bookList
        }
        bookList = FileUtil.getFileListInfo()

        val files = Environment.getExternalStorageDirectory().listFiles()

        var hasNew = false
        for (file in files) {
            if (file.name.toLowerCase() == "documents") {
                val subItems = file.listFiles()

                for (subItem in subItems) {
                    val name = subItem.name
                    //if (name.endsWith("pdf") || name.endsWith("PDF")) {
                        var added = false
                        for (item in bookList) {
                            if (item.bookName.equals(name, ignoreCase = true)) {
                                added = true
                                break
                            }
                        }
                        if (!added) {
                            hasNew = true
                            bookList.add(BookBean(name, 1))
                        }
                    //}
                }
                break
            }
        }
        if (hasNew) {
            saveChange()
        }
        return bookList
    }

    fun isBookListInit(): Boolean{
        return this::bookList.isInitialized
    }

    fun addItem(bookBean: BookBean){
        bookList.add(bookBean)
        FileUtil.writeFileInfo(bookList)
    }

    fun addItem(index: Int, bookBean: BookBean){
        bookList.add(index, bookBean)
        FileUtil.writeFileInfo(bookList)
    }

    fun removeItem(position: Int){
        bookList.removeAt(position)
        FileUtil.writeFileInfo(bookList)
    }

    fun saveChange(){
        FileUtil.writeFileInfo(bookList)
    }

    fun hasItem(fileName:String, type:Int): Boolean{
        if (isBookListInit()) {
            for (item in bookList) {
                if (item.bookName.equals(fileName) && item.type == type) {
                    return true
                }
            }
        }
        return false
    }
}